package com.qfedu.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qfedu.dao.PermissionRepository;
import com.qfedu.pojo.entity.Permission;
import com.qfedu.pojo.req.PermissionReq;
import com.qfedu.pojo.resp.BaseResp;
import com.qfedu.service.PermissionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    PermissionRepository permissionRepository;

    @Override
    public BaseResp findAllPermission(Integer page, Integer size) {
//        //1.在执行全查之前开启分页
//        PageHelper.startPage(page, size);
//        //2.执行全查操作
//        List<Permission> permissions = permissionRepository.findAll();
//        //3.将查询结果放入分页对象中完成分页操作
//        PageInfo<Permission> adminPageInfo = new PageInfo<>(permissions);
//        return new BaseResp(1, "查询成功", adminPageInfo.getList(), adminPageInfo.getTotal());

        PageRequest of = PageRequest.of(page - 1, size);
        Page<Permission> permissions = permissionRepository.findAll(of);
        return new BaseResp(1,"查询成功",permissions.getContent(),permissions.getTotalElements());
    }

    @Override
    public BaseResp addOrUpdPermission(PermissionReq permissionReq) {
        Permission permission = new Permission();
        //将PermissionReq中接收的请求参数复制到permission实体类中
        BeanUtils.copyProperties(permissionReq, permission);
        permissionRepository.saveAndFlush(permission);
        return new BaseResp(1, "更新成功！", null, null);
    }

    @Override
    public BaseResp delPermission(PermissionReq permissionReq) {
        permissionRepository.deleteById(permissionReq.getId());
        return new BaseResp(1, "更新成功！", null, null);
    }
}
